package com.yunkecn.redispubsub;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Random;

public class RegisterHandler {

    @Autowired
    RedisTemplate redisTemplate;


    public void init(RedisMessageListenerContainer redisMessageListenerContainer) {
        redisMessageListenerContainer.addMessageListener(new RegisterMessageListener(), new ChannelTopic("register"));
    }

    private class RegisterMessageListener implements MessageListener {

        /**
         * Callback for processing received objects through Redis.
         *
         * @param message message must not be {@literal null}.
         * @param pattern pattern matching the channel (if specified) - can be {@literal null}.
         */
        @Override
        public void onMessage(Message message, byte[] pattern) {
            RegisterMessage m = (RegisterMessage) redisTemplate.getValueSerializer().deserialize(message.getBody());
            int id = new Random().nextInt(10000);
            System.out.println("接收到消息" + id);
            m.setId(id);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread());
            System.out.println(m);
        }
    }
}


